package client;

import defaultProperties.window;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JOptionPane;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * main.java
 *
 * Created on Sep 30, 2013, 2:27:00 PM
 */
/**
 *
 * @author GON
 */
public class main extends window implements Runnable {

    int posX = 0, posY = 0;
    String serverIP;
    String username;
    int serverPort;
    private Socket socket;
    private BufferedWriter bw;
    private BufferedReader br;
    private boolean connected = false;
    setup parent;
    ArrayList chatWindows = new ArrayList();
    ArrayList groups = new ArrayList();
    ArrayList groupMembers = new ArrayList();
    ArrayList peopleOnline;

    public main(String uname, String ip, int port, setup p) {

        // add default window propertes
        super.addWindowProperties(this);

        System.out.println("USERNAME: " + uname);
        serverIP = ip;
        serverPort = port;
        username = uname;
        parent = p;
        initComponents();
        groups.add("EVERYONE");

        // add double click event to lists
        everyoneList.addMouseListener(new MouseAdapter() {

            @Override
            public void mouseClicked(MouseEvent evt) {
                try {
                    JList list = (JList) evt.getSource();
                    if (evt.getClickCount() == 2) {
                        int index = list.locationToIndex(evt.getPoint());
                        int windowIndex = 0;
                        System.out.println(index);
                        boolean windowOpen = false;
                        for (int i = 0; i < chatWindows.size(); i++) {
                            if (((chat) chatWindows.get(i)).getWindowName().equals(list.getSelectedValue().toString())) {
                                windowOpen = true;
                                windowIndex = i;
                                break;
                            }
                        }

                        if (!windowOpen) {
                            chat gui = new chat(list.getSelectedValue().toString(), socket, username, false, null, null);
                            gui.setVisible(true);
                            chatWindows.add(gui);
                        } else {
                            ((chat) chatWindows.get(windowIndex)).setVisible(true);
                        }
                    }
                } catch (NullPointerException e) {
                }
            }
        });

        groupsList.addMouseListener(new MouseAdapter() {

            @Override
            public void mouseClicked(MouseEvent evt) {
                try {
                    JList list = (JList) evt.getSource();
                    if (evt.getClickCount() == 2) {
                        int index = list.locationToIndex(evt.getPoint());
                        int windowIndex = 0;
                        boolean windowOpen = false;
                        for (int i = 0; i < chatWindows.size(); i++) {
                            if (((chat) chatWindows.get(i)).getWindowName().equals(list.getSelectedValue().toString())) {
                                windowOpen = true;
                                windowIndex = i;
                                break;
                            }
                        }

                        if (!windowOpen) {
                            chat gui = new chat(list.getSelectedValue().toString(), socket, username, true, groupMembers, peopleOnline);
                            gui.setVisible(true);
                            chatWindows.add(gui);
                        } else {
                            ((chat) chatWindows.get(windowIndex)).setVisible(true);
                        }
                    }
                } catch (NullPointerException e) {
                }
            }
        });

        this.connect();
    }

    /** Creates new form main */
    public main() {
//        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    private void initComponents() {//GEN-BEGIN:initComponents

        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenu2 = new javax.swing.JMenu();
        jScrollPane1 = new javax.swing.JScrollPane();
        jList1 = new javax.swing.JList();
        jSeparator1 = new javax.swing.JSeparator();
        jButton2 = new javax.swing.JButton();
        jPanel4 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        jPanel3 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        everyoneList = new javax.swing.JList();
        jLabel2 = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        jScrollPane3 = new javax.swing.JScrollPane();
        groupsList = new javax.swing.JList();
        addGroupButton = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        userNameLabel = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        statusBar = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();
        jLabel11 = new javax.swing.JLabel();

        jMenu1.setText("File");
        jMenuBar1.add(jMenu1);

        jMenu2.setText("Edit");
        jMenuBar1.add(jMenu2);

        jList1.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jScrollPane1.setViewportView(jList1);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("C.O.C. Messenger");
        setBackground(new java.awt.Color(255, 255, 255));
        setLocationByPlatform(true);
        setUndecorated(true);

        jButton2.setText("jButton2");

        jPanel4.setBackground(new java.awt.Color(255, 255, 255));
        jPanel4.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(204, 204, 204), 3));

        jLabel1.setBackground(new java.awt.Color(255, 255, 255));
        jLabel1.setFont(new java.awt.Font("Segoe UI Light", 0, 14));
        jLabel1.setForeground(new java.awt.Color(0, 102, 0));
        jLabel1.setText("C.O.C. Messenger");
        jLabel1.setOpaque(true);

        jTabbedPane1.setBackground(new java.awt.Color(255, 255, 255));
        jTabbedPane1.setToolTipText("");
        jTabbedPane1.setAutoscrolls(true);
        jTabbedPane1.setFont(new java.awt.Font("Segoe UI Light", 0, 14));

        jPanel3.setBackground(new java.awt.Color(241, 241, 241));

        jScrollPane2.setBorder(null);

        everyoneList.setBorder(javax.swing.BorderFactory.createMatteBorder(2, 2, 2, 2, new java.awt.Color(153, 153, 153)));
        everyoneList.setFont(new java.awt.Font("Segoe UI Light", 0, 14));
        everyoneList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane2.setViewportView(everyoneList);

        jLabel2.setFont(new java.awt.Font("Segoe UI Light", 0, 14));
        jLabel2.setText("Who's Online:");

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 275, Short.MAX_VALUE)
                    .addComponent(jLabel2))
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 279, Short.MAX_VALUE)
                .addContainerGap())
        );

        jTabbedPane1.addTab("Everyone", jPanel3);

        jPanel1.setBackground(new java.awt.Color(241, 241, 241));

        jLabel3.setFont(new java.awt.Font("Segoe UI Light", 0, 14));
        jLabel3.setText("Your Groups:");

        groupsList.setFont(new java.awt.Font("Segoe UI Light", 0, 14));
        groupsList.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "EVERYONE" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        groupsList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane3.setViewportView(groupsList);

        addGroupButton.setFont(new java.awt.Font("Segoe UI Light", 0, 14));
        addGroupButton.setText("+ Add");
        addGroupButton.setBorderPainted(false);
        addGroupButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addGroupButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 275, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 123, Short.MAX_VALUE)
                        .addComponent(addGroupButton)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(addGroupButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 270, Short.MAX_VALUE)
                .addContainerGap())
        );

        jTabbedPane1.addTab("Groups", jPanel1);

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/close.png"))); // NOI18N
        jButton1.setBorderPainted(false);
        jButton1.setContentAreaFilled(false);
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        userNameLabel.setFont(new java.awt.Font("Segoe UI Light", 0, 24));
        userNameLabel.setText("Gon");
        userNameLabel.setMaximumSize(new java.awt.Dimension(250, 32));

        jLabel6.setForeground(new java.awt.Color(204, 204, 204));
        jLabel6.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel6.setText("__________________________________________________");
        jLabel6.setFocusable(false);
        jLabel6.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jLabel6.setInheritsPopupMenu(false);
        jLabel6.setRequestFocusEnabled(false);
        jLabel6.setVerifyInputWhenFocusTarget(false);

        jLabel7.setText("jLabel7");

        statusBar.setFont(new java.awt.Font("Segoe UI Light", 0, 14));
        statusBar.setForeground(new java.awt.Color(102, 102, 102));
        statusBar.setText("Status: Connected to 127.0.0.1 : 12345");

        jLabel9.setForeground(new java.awt.Color(204, 204, 204));
        jLabel9.setText("__________________________________________________");

        jLabel10.setIcon(new javax.swing.ImageIcon(getClass().getResource("/poll_topic.png"))); // NOI18N

        jLabel11.setIcon(new javax.swing.ImageIcon(getClass().getResource("/info.png"))); // NOI18N

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(statusBar)
                    .addComponent(jTabbedPane1, 0, 0, Short.MAX_VALUE)
                    .addComponent(jLabel9, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(userNameLabel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel4Layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addComponent(jLabel10)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 94, Short.MAX_VALUE)
                        .addComponent(jLabel11)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jLabel6))
                .addContainerGap())
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel4Layout.createSequentialGroup()
                        .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel10))
                        .addGap(15, 15, 15)
                        .addComponent(userNameLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(jLabel11, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton1, javax.swing.GroupLayout.Alignment.LEADING)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel6)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 358, Short.MAX_VALUE)
                .addGap(1, 1, 1)
                .addComponent(jLabel9)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(statusBar, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        jPanel4.getAccessibleContext().setAccessibleName("");

        getAccessibleContext().setAccessibleName("C.O.C. MEssenger");

        pack();
    }//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        try {
            bw.write("disXXX " + username);
            bw.newLine();
            bw.flush();
            System.exit(0);
        } catch (IOException ex) {
            Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
        }
}//GEN-LAST:event_jButton1ActionPerformed

    private void addGroupButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addGroupButtonActionPerformed
        final String[] gr = new String[groups.size() + 1];
        for (int i = 0; i < groups.size(); i++) {
            gr[i] = (String) groupsList.getModel().getElementAt(i);
        }
        String newGroupName = JOptionPane.showInputDialog(null, "Input Group Name");
        gr[groups.size()] = newGroupName;
        groups.add(newGroupName);

        groupsList.setModel(new javax.swing.AbstractListModel() {

            String[] strings = gr;

            public int getSize() {
                return strings.length;
            }

            public Object getElementAt(int i) {
                return strings[i];
            }
        });
    }//GEN-LAST:event_addGroupButtonActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addGroupButton;
    private javax.swing.JList everyoneList;
    private javax.swing.JList groupsList;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JList jList1;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JLabel statusBar;
    private javax.swing.JLabel userNameLabel;
    // End of variables declaration//GEN-END:variables

    public void connect(String uname, String ip, int port) {
        this.username = uname;
        this.serverIP = ip;
        this.serverPort = port;

        this.connect();
    }

    private void connect() {
        try {
            socket = new Socket(serverIP, serverPort);
            br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));

            Thread th;
            th = new Thread(this);
            th.start();

            bw.write("username: " + username);
            bw.newLine();
            bw.flush();

            statusBar.setText("Status: Connected to " + serverIP + " : " + serverPort + ".");
            connected = true;
        } catch (UnknownHostException ex) {
            this.setVisible(false);
            parent.setVisible(true);
            JOptionPane.showMessageDialog(null, "Cannot connect to server!");
            Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            this.setVisible(false);
            parent.setVisible(true);
            JOptionPane.showMessageDialog(null, "Cannot connect to server!");
            Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    public void run() {
        String msg = "";
        BufferedWriter out = null;
        while (true) {
            try {
                msg = br.readLine();
                System.out.println("Message from server: " + msg);
                if (msg.equals("invalidXUserXNameX32X12")) {
                    this.setVisible(false);
                    parent.setVisible(true);
                    JOptionPane.showMessageDialog(null, "Username Already in use");
                } else if (msg.startsWith("validXUserXNameX32X11")) {
                    userNameLabel.setText(username);
                    parent.setVisible(false);
                    this.setVisible(true);
                } else if (msg.startsWith("newClientsList,")) { // a user has been logged in or diconnected
                    String[] temp = msg.split(",");
                    int size = temp.length - 1;
                    final String[] string = new String[size];
                    for (int i = 1; i < temp.length; i++) {
                        if (!username.equals(temp[i])) {
                            string[i - 1] = temp[i];
                        }
                    }

                    // repaint the list
                    everyoneList.setModel(new javax.swing.AbstractListModel() {

                        String[] strings = string;

                        public int getSize() {
                            return strings.length;
                        }

                        public Object getElementAt(int i) {
                            return strings[i];
                        }
                    });

                    // update the list of online users
                    peopleOnline = new ArrayList();
                    for (int i = 1; i < temp.length; i++) {
                        if (!temp[i].equals(username)) {
                            peopleOnline.add(temp[i]);
                        }
                    }

                    // check the windows
                    for (int i = 0; i < chatWindows.size(); i++) {
                        if (!peopleOnline.contains(((chat) chatWindows.get(i)).getWindowName())) {
                            System.out.println(((chat) chatWindows.get(i)).getWindowName() + " has disconnected");
                            ((chat) chatWindows.get(i)).userDisconnected();
                            chatWindows.remove(i);
                        }
                    }
                } else if (msg.startsWith("sent")) {
                    msg = msg.substring(5, msg.length());
                    System.out.println("cMessage: " + msg);
                    String[] m = msg.split(":");
                    String from = m[0];
                    String to = m[1];
                    String message = "";

                    int j;
                    for (j = 2; j < m.length - 1; j++) {
                        message += m[j] + ":";
                    }
                    message += m[j];

                    boolean windowOpen = false;
                    int windowIndex = 0;
                    if (!to.startsWith("GROUPXX1X01")) {
                        for (int i = 0; i < chatWindows.size(); i++) {
                            if (((chat) chatWindows.get(i)).getWindowName().equals(from)) {
                                windowOpen = true;
                                ((chat) chatWindows.get(i)).setVisible(true);
                                windowIndex = i;
                            }
                        }
                        if (!windowOpen) {
                            chat gui = new chat(from, socket, username, false, null, null);
                            gui.setVisible(true);
                            windowOpen = true;
                            chatWindows.add(gui);
                            windowIndex = chatWindows.size() - 1;
                        }

                        // trim message:
                        String[] k = message.split(" ");
                        message = "";
                        int i;
                        for (i = 2; i < k.length - 1; i++) {
                            message += k[i] + " ";
                        }
                        message += k[i];
                        System.out.println(message);
                        ((chat) chatWindows.get(windowIndex)).writeToPanel(message);
                    } else {
                        to = to.substring(12, to.length());
                        windowOpen = false;
                        for (int i = 0; i < chatWindows.size(); i++) {
                            if (((chat) chatWindows.get(i)).getWindowName().equals(to)) {
                                ((chat) chatWindows.get(i)).setVisible(true);
                                ((chat) chatWindows.get(i)).writeToPanel(message);
                                windowOpen = true;
                            }
                        }
                        if (!windowOpen) {
                            chat gui = new chat(to, socket, username, true, groupMembers, peopleOnline);
                            gui.setVisible(true);
                            gui.writeToPanel(message);
                            chatWindows.add(gui);
                        }
                    }
                } else if (msg.startsWith("newGroupMembers")) {
                    String gMembers = msg.substring(16, msg.length());
                    String[] members = gMembers.split(",");
                    String groupName = members[0];
                    if (!groups.contains(groupName)) {
                        ArrayList temp = new ArrayList();
                        int count = 0;
                        for (int i = 1; i < members.length; i++) {
                            System.out.println("MEMBER: " + members[i]);
                            if (!members[i].equals(username)) {
                                temp.add(members[i]);
                            }
                        }
                        System.out.println("GroupMembers: " + temp);
                        chat gui = new chat(groupName, socket, username, true, temp, peopleOnline);
                        chatWindows.add(gui);

                        final String[] gr = new String[groups.size() + 1];
                        for (int i = 0; i < groups.size(); i++) {
                            gr[i] = (String) groupsList.getModel().getElementAt(i);
                        }
                        gr[groups.size()] = groupName;
                        groups.add(groupName);

                        groupsList.setModel(new javax.swing.AbstractListModel() {

                            String[] strings = gr;

                            public int getSize() {
                                return strings.length;
                            }

                            public Object getElementAt(int i) {
                                return strings[i];
                            }
                        });
                    }
                } else if (msg.startsWith("fileSent")) {
                    System.out.println("TEST: " + msg);
                    String[] temp = msg.split(":");
                    String fileName = temp[2];
                    String sender = temp[2].split("_")[0];
                    String to = "";

                    if (temp[1].equals("X")) {
                        to = sender;
                    } else if (temp[1].equals("GROUPXX1X01")) {
                        to = temp[2];
                        fileName = temp[3];
                        sender = temp[3].split("_")[0];
                    } else {
                        to = temp[1];
                    }

                    Boolean windowOpen = false;
                    if (sender.equals(username)) {
                        windowOpen = true;
                    } else {
                        for (int i = 0; i < chatWindows.size(); i++) {
                            if (((chat) chatWindows.get(i)).getWindowName().equals(to)) {
                                ((chat) chatWindows.get(i)).setVisible(true);
                                ((chat) chatWindows.get(i)).fileRecieved(fileName, sender);
                                windowOpen = true;
                            }
                        }
                    }
                    if (!windowOpen) {
                        chat gui;
                        if (to.equals("GROUPXX1X01")) {
                            gui = new chat(to, socket, username, true, null, peopleOnline);
                        } else {
                            gui = new chat(to, socket, username, false, null, peopleOnline);
                        }
                        gui.setVisible(true);
                        gui.fileRecieved(fileName, sender);
                        chatWindows.add(gui);
                    }
                } else if (msg.startsWith("RecieveFileXXKJK")) {
                    if (msg.startsWith("RecieveFileXXKJKStart")) {
                        String fName = msg.split(":")[1];
                        System.out.println("FILENAME: " + fName);
                        out = new BufferedWriter(new FileWriter(fName));
                    } else if (msg.startsWith("RecieveFileXXKJKEnd")) {
                        out.close();
                        System.out.println("file recieved");
                    } else {
                        out.append(msg.substring(17));
                    }
                } else if (msg.equals("serverDown")) { // hide all open windows except the parent, setup
                    this.setVisible(false);
                    for (int i = 0; i < chatWindows.size(); i++) {
                        if (((JFrame) chatWindows.get(i)).isVisible()) {
                            ((JFrame) chatWindows.get(i)).setVisible(false);
                        }
                    }
                    parent.setVisible(true);
                    JOptionPane.showMessageDialog(null, "The server has shut down!", "SERVER ERROR", 1);
                }
            } catch (Exception h) {
            }
        }
    }
}
